﻿// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Abp.Authorization;
using Abp.Web.Models;
using Abp.Web.Mvc.Models;
using L._52Abp.Extensions;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace GCT.Foundation.Controllers
{

    public class ErrorController : FoundationTemplateControllerBase
    {
        private static readonly Exception DEFAULT_EXCEPTION = new Exception("Unhandled exception!");

        private readonly IErrorInfoBuilder _errorInfoBuilder;

        public ErrorController(IErrorInfoBuilder errorInfoBuilder)
        {
            _errorInfoBuilder = errorInfoBuilder;
        }

        public IActionResult Index(int statusCode = 0)
        {
            return this.Handler(statusCode);
        }

        public ActionResult E404()
        {
            return View("Error404");
        }

        public IActionResult Handler(int statusCode = 0)
        {
            var actionResult = this.AjaxRequestError(statusCode);
            if (actionResult != null)
            {
                return actionResult;
            }
            if (statusCode == 404 || statusCode == 403)
            {
                return View("Error404");
            }

            var exception = this.GetException();
            var errorInfo = _errorInfoBuilder.BuildForException(exception);

            return View(
                "~/Views/Error/Error.cshtml",
                new ErrorViewModel(
                    errorInfo,
                    exception
                )
            );
        }

        /// <summary>
        /// Ajax 异常处理
        /// </summary>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        protected IActionResult AjaxRequestError(int statusCode = 0)
        {
            if (!HttpContext.IsAjax())
            {
                return null;
            }

            var exception = this.GetException();
            var errorInfo = _errorInfoBuilder.BuildForException(exception);
            return Json(
                new AjaxResponse<ErrorInfo>(errorInfo, exception is AbpAuthorizationException)
                );
        }

        /// <summary>
        /// 获取当前的异常，如果没有，那么抛出默认异常
        /// </summary>
        /// <returns></returns>
        protected Exception GetException()
        {
            var exceptionHandler = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var exception = exceptionHandler?.Error ?? DEFAULT_EXCEPTION;

            return exception;
        }
    }
}
